package study.javaee.practice.handler;


import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import study.javaee.practice.common.api.CommonResult;
import study.javaee.practice.common.exception.ApiException;

import javax.validation.ConstraintViolationException;


@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(value = ApiException.class)
    public CommonResult<Object> handle(ApiException exception){
        return new CommonResult<>(exception.getApiErrorCode().getCode(), exception.getMessage());
    }

    @ExceptionHandler(value = BindException.class)
    public CommonResult<Object> handle(BindException exception){
        BindingResult result = exception.getBindingResult();
        ObjectError err = result.getAllErrors().get(0);
        return CommonResult.validateFailed(err.getDefaultMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult<Object> handle(MethodArgumentNotValidException exception){
        BindingResult result = exception.getBindingResult();
        ObjectError err = result.getAllErrors().get(0);
        return CommonResult.validateFailed(err.getDefaultMessage());
    }

    @ExceptionHandler(value = ConstraintViolationException.class)
    public CommonResult<Object> handle(ConstraintViolationException exception){
        return CommonResult.validateFailed(exception.getMessage());
    }
    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public CommonResult<Object> handle(MissingServletRequestParameterException exception){
        return CommonResult.validateFailed(exception.getMessage());
    }
}
